import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Button } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useHistory } from 'react-router-dom';
import {
  getRestaurantListAPI,
  DataType,
  recommendRestaurantsAPI,
} from '@/service/restaurant';

const App: React.FC = () => {
  const [data, setData] = useState<DataType[]>();
  const [loading, setLoading] = useState(false);

  const history = useHistory();

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '图片',
        dataIndex: 'image',
        render: (image) => (
          <img
            src={`http://localhost:10001/ftp/download?fileName=${image}&path=dish`}
            alt=""
            width="100"
            height="100"
          />
        ),
        width: '10%',
      },
      {
        title: '店铺名称',
        dataIndex: 'name',
        sorter: true,
        render: (name) => `${name}`,
        width: '15%',
      },
      {
        title: '地址',
        dataIndex: 'address',
        render: (classify) => `${classify}`,
        width: '10%',
      },
      {
        title: '评分',
        dataIndex: 'score',
        sorter: true,
        render: (number) => `${number} 分`,
        width: '10%',
      },
      {
        width: '10%',
        title: '进店',
        render: (record) => (
          <Button
            onClick={() => {
              localStorage.setItem('restaurant', record.id);
              history.push({
                pathname: '/userDish',
              });
            }}
          >
            进店
          </Button>
        ),
      },
    ],
    [],
  ); // 添加空的依赖项数组
  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);
    const res = await recommendRestaurantsAPI(26);
    setData(res);
  }, []);

  //监听tableParams的变化
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        scroll={{ y: 530 }}
      />
    </div>
  );
};
export default App;
